<template>
  <div ref="muliTags"  class="muli-tags" @click='focus'>
    <el-tag
      v-for="tag in tags"
      :key="tag.name"
      closable
      @close="handleClose(tag)"
    >
      {{tag}}
    </el-tag>
    <input type="text"
           placeholder="请输入"
           ref='input'
           @keyup.enter="handleInputConfirm"
           @keydown.delete="handleDel"
           @blur="handleBlur"
           v-model='current'>
  </div>
</template>

<script>
export default {
  props: {
  },
  name: 'tagsInput',
  data () {
    return {
      current: '',
      tags: []
    }
  },
  mounted () {},
  methods: {
    focus () {
      this.$refs.input.focus()
      this.$refs.muliTags.style = 'border-color: #409EFF'
    },
    handleInputConfirm () {
      let inputVal = this.current.trim()
      if (inputVal && this.tags.indexOf(inputVal) === -1) {
        this.tags.push(inputVal)
        this.$emit('input', this.tags)
      } else {
        return
      }
      this.current = ''
    },
    handleBlur () {
      this.$refs.muliTags.style = 'border-color: #DCDFE6'
    },
    handleClose (tag) {
      this.tags.splice(this.tags.indexOf(tag), 1)
      this.$emit('input', this.tags)
    },
    handleDel (e) {
      // 当文本框内没有值，再按回退键，则删除最后一个tag
      if (!e.target.value.length) {
        this.tags.pop()
        this.$emit('input', this.tags)
      }
    }
  }
}
</script>

<style lang="scss">
  input,textarea{
    &::placeholder {
      color: #bbb;
    }

    &::-webkit-input-placeholder {
      /* WebKit browsers 适配谷歌 */
      color: #bbb;
    }
  }
  .muli-tags {
    /*width: 400px;*/
    min-height: 40px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    align-items: center;
    box-sizing: border-box;
    width: 100%;
    border-radius: 4px;
    padding: 5px 10px;
    border: 1px solid #DCDFE6;
    color: #606266;
    font-size: inherit;
    /*height: 40px;*/
    /*line-height: 40px;*/
    .input {
      height: 100%;
      width: 80px;
      .el-input__inner {
        padding: 0;
        outline:  none;
        border:none;
        background: transparent;
      }
    }
    input {
      height: 100%;
      width: 80px;
      padding: 0;
      outline:  none;
      border:none;
      background: transparent;
    }
    .el-tag {
      margin: 0 5px 3px 0;
    }
  }
</style>
